﻿using HealthcareSystem.API.Read.Application.Command.Element.ElementCommand;
using HealthcareSystem.API.Read.Application.Command.KnowledgeCommand;
using HealthcareSystem.API.Read.DTO.Element;
using HealthcareSystem.API.Read.DTO.KnowledgeShowDto;
using HealthcareSystem.Domain.BasicSettings.Element_classification;
using HealthcareSystem.Domain.BasicSettings.FormManagement;
using MediatR;
using Microsoft.EntityFrameworkCore.Metadata.Internal;
using System.ComponentModel;
using WeekExam.PassPort.ErrorCode;
using WeekExam.PassPort.Infrastructure.Interface;
using static Microsoft.EntityFrameworkCore.DbLoggerCategory;

namespace HealthcareSystem.API.Read.Application.CommandHandel.Element.ElementCommandHandler
{
    public class ShowElementCommandHandel : IRequestHandler<ShowElementCommand, ApiResult<ApiPaging<List<ShowElementDto>>>>
    {
        IBaseRepository<Managementelements> managementelementsHandler;
        IBaseRepository<Elementtype> elementTypeHandler;

        public ShowElementCommandHandel(IBaseRepository<Managementelements> managementelementsHandler, IBaseRepository<Elementtype> elementTypeHandler)
        {
            this.managementelementsHandler = managementelementsHandler;
            this.elementTypeHandler = elementTypeHandler;
        }
        /// <summary>
        /// 元素显示
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public Task<ApiResult<ApiPaging<List<ShowElementDto>>>> Handle(ShowElementCommand request, CancellationToken cancellationToken)
        {
            ApiResult<ApiPaging<List<ShowElementDto>>> result = new ApiResult<ApiPaging<List<ShowElementDto>>>();
            result.Code = ResultCode.查询成功;
            result.Message = ResultCode.查询成功.ToString();

            var list = from a in managementelementsHandler.GetAll()
                       from b in elementTypeHandler.GetAll()
                       where a.IsDel == true && b.ElementtypeId == a.ElementCategory
                       select new ShowElementDto
                       {
                           ElementId = a.ElementId,
                           ElementCode = a.ElementCode,
                           ElementName = a.ElementName,
                           ElementalAbbreviation = a.ElementalAbbreviation,
                           ElementType = a.ElementType,
                           Elementalform = a.Elementalform,
                           ElementCategory = b.ElementtypeId,
                           ElementNum = b.ElementNum,
                       };

            // ====== 添加查询过滤条件 ======

            // 1. 按元素名称（模糊查询）
            if (!string.IsNullOrWhiteSpace(request.ElementName))
            {
                list = list.Where(x => x.ElementName.Contains(request.ElementName));
            }

            // 2. 按元素类别（分类）过滤
            if (request.ElementCategory.HasValue && request.ElementCategory.Value > 0)
            {
                list = list.Where(x => x.ElementCategory == request.ElementCategory.Value);
            }

            // 3. 按状态过滤（Elementalform: true=启用, false=停用）
            if (request.Elementalform.HasValue)
            {
                list = list.Where(x => x.Elementalform == request.Elementalform.Value);
            }

            var totalCount = list.Count();
            var totalPage = (int)Math.Ceiling((totalCount * 1.0) / request.pageSize);
            list = list.OrderBy(x => x.ElementId).Skip((request.pageIndex - 1) * request.pageSize).Take(request.pageSize);


            ApiPaging<List<ShowElementDto>> paging = new ApiPaging<List<ShowElementDto>>();
            paging.totalPage = totalPage;
            paging.totalCount = totalCount;
            paging.Data = list.ToList();
            result.Data = paging;

            return Task.FromResult(result);
        }
    }
}
